package com.dzt.androidframework.photo;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;

import com.dzt.androidframework.R;
import com.dzt.androidframework.activity.ActivityTitle;
import com.dzt.androidframework.activity.MainActivity;
import com.dzt.androidframework.photo.adapter.GridViewAdapter;
import com.dzt.androidframework.utils.JToastKit;

import org.xutils.view.annotation.ViewInject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 拍照，图库多选图上传
 */
public class CameraActivity extends ActivityTitle implements
		AdapterView.OnItemClickListener,
		AdapterView.OnItemLongClickListener {
	/**
	 * 最大上传图片数量
	 */
	public static final int MAX_IMAGECOUNT = 9;

	/**
	 * 调用相机拍照
	 */
	public static final int CALL_CAMERA = 1;

	/**
	 * 选择图片（单选）标识数据
	 */
	public static final int SELECTIMAGE_ONE = 2;

	/**
	 * 选择图片（多选）标识数据
	 */
	public static final int SELECTIMAGE_MORE = 3;

	/**
	 * 拍照图片存放文件夹
	 */
	public static final String PHOTO_FILE_PATH = Environment.getExternalStorageDirectory() + File.separator + MainActivity.class.getPackage().getName() + File.separator + "no_upload_media";
	@ViewInject(R.id.main_data_gridView)
	private GridView gridView;

	private List<ImageModel> imageList = new ArrayList<>();
	private GridViewAdapter adapter;

	private Intent intent; // 页面跳转（拍照，相册选图）
	private String current_datetime; // 当前时间
	private String photoName; // 图片文件名
	private String photoSavePath; // 图片存储位置

	@Override
	protected int getLayoutId() {
		return R.layout.activity_camera;
	}

	@Override
	protected void initParams() {
		setTitleView(R.string.text_camera);
		gridView.setOnItemClickListener(this);
		gridView.setOnItemLongClickListener(this);
		ImageModel imageModel = new ImageModel();
		imageModel.setSpareImage(R.drawable.addimage);
		imageList.add(imageModel);
		adapter = new GridViewAdapter(this, imageList, View.GONE);
		gridView.setAdapter(adapter);
	}

	@Override
	protected void initData(Bundle savedInstanceState) {

	}

	@Override
	protected String[] initPermissions() {
		return new String[0];
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
		// 获取点击的对象
		ImageModel imageModel = imageList.get(i);
		String pathStr = imageModel.getImagePath();
		int spareImage = imageModel.getSpareImage();

		if (pathStr.equals("") && spareImage != 0) { // 点击的是添加照片的对象
			final String[] items = {"拍照", "相册选择(单选)", "相册选择(多选)"};
			new AlertDialog.Builder(this)
					.setTitle("请选择获取图片方式")
					.setItems(items, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							imageList.remove(imageList.size() - 1); // 现将加号移除（有加号才能显示此按钮）
							switch (which) {
								case 0:
									// 调用相机拍照并保存拍照文件到指定目录
									callCameraTakePhoto();
									break;
								case 1:
									// 图片单选，直接跳转至系统图片库
									intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
									startActivityForResult(intent, SELECTIMAGE_ONE);
									break;
								case 2:
									// 移除加号，剩下的路径传至第二界面
									// 跳转至图片多选页面SelectMoreImageActivity
									intent = new Intent(CameraActivity.this, SelectMoreActivity.class);
									// 设置传递参数
									ArrayList<String> photoArrayList = new ArrayList<>();
									for (ImageModel imageModel : imageList) {
										photoArrayList.add(imageModel.getImagePath());
									}
									intent.putExtra("imageCount", photoArrayList.size()); // 当前已选择的数量
									intent.putStringArrayListExtra("photoArrayList", photoArrayList); // 当前已选择的路径
									startActivityForResult(intent, SELECTIMAGE_MORE); // 跳转到第二个页面
									break;
							}
						}
					})
					.setNegativeButton("取消", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					}).show();
		}
	}

	/**
	 * 调用相机拍照并存储照片
	 */
	private void callCameraTakePhoto() {
		Date currentDate = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINESE);
		current_datetime = sdf.format(currentDate); // 初始化当前时间值
//		路径规则：SD卡路径（内部存储）/packageName/no_upload_media/yyyyMMddHHmmss.jpg
		photoName = current_datetime + ".jpg"; // 初始化图片文件名
		photoSavePath = PHOTO_FILE_PATH + File.separator + photoName; // 初始化文件夹位置
		Log.e("path", photoSavePath);

		init_pic_dir(PHOTO_FILE_PATH); // 查询并创建文件夹

		// 启动相机并拍照
		intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(photoSavePath)));
		startActivityForResult(intent, CALL_CAMERA);
	}

	/**
	 * 查询指定路径文件是否存在，若不存在就直接创建
	 *
	 * @param path 指定路径
	 */
	private void init_pic_dir(String path) {
		File d = new File(path + File.separator);
		if (!d.exists()) {
			d.mkdirs();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			switch (requestCode) {
				case CALL_CAMERA:
					// 调用相机拍照
					// 思路：将加号移除--调用拍照返回数据--将数据添加至集合--在onRestart中判断是否添加加号并刷新adapter
					if (data == null) {
						// 若返回结果为空，则获取之前文件保存路径
						// 创建对象并添加至集合
						ImageModel imageModel = new ImageModel();
						imageModel.setImagePath(photoSavePath);
						imageList.add(imageModel);
					}
					break;
				case SELECTIMAGE_ONE:
					// 调用系统图库单选
					// 思路：将加号移除--调用图库选图片--获取回文数据--将回文数据添加至集合--在onRestart中判断是否添加加号并刷新adapter
					if (data != null) {
						// 获取相册选择结果（保存路径）

						Uri selectedImage = data.getData();
						String[] filePathColumn = {MediaStore.Images.Media.DATA};
						Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
						cursor.moveToFirst();

						int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
						final String picturePath = cursor.getString(columnIndex);

						// 创建对象并添加至集合
						ImageModel imageModel = new ImageModel();
						imageModel.setImagePath(picturePath);
						imageList.add(imageModel);
					}
					break;
				case SELECTIMAGE_MORE:
					// 调用图库多选
					// 思路：先将加号移除--调用图库选图片--获取回文数据--将回文数据添加至集合--在onRestart中判断是否添加加号并刷新adapter
					if (data != null) {
						// 如果回文不为空，获取回传的List值
						ArrayList<String> returnPathList = data.getStringArrayListExtra("returnPathList");
						imageList.removeAll(imageList); // 清空当前显示的List

						// 创建对象并添加至本界面的List集合
						ImageModel imageModel;
						for (String string : returnPathList) {
							imageModel = new ImageModel();
							imageModel.setImagePath(string);
							imageList.add(imageModel);
						}
					} else {
						JToastKit.getInstance().showMessage("data为空！");
						ImageModel model = new ImageModel();
						model.setSpareImage(R.drawable.addimage);
						imageList.add(model);
						adapter.notifyDataSetChanged(); // 通知adapter刷新
					}
					break;
			}
		}
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
		ImageModel imageModel = imageList.get(position);
		String pathStr = imageModel.getImagePath();
		int spareImage = imageModel.getSpareImage();
		if (!pathStr.equals("") && spareImage == 0) {
			// 图片（非添加标志图）长按事件处理
			new AlertDialog.Builder(this).setTitle("操作提示")
					.setMessage("长按删除该图片（原相册中的图片不会删除），是否删除？")
					.setPositiveButton("删除", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							for (int i = 0; i < imageList.size(); i++) {
								String pathStr = imageList.get(i).getImagePath();
								if (!pathStr.equals("") && i == imageList.size() - 1) {
									ImageModel imageModel = new ImageModel();
									imageModel.setSpareImage(R.drawable.addimage);
									imageList.add(imageModel);
								}
							}
							imageList.remove(position);
							adapter.notifyDataSetChanged();
						}
					})
					.setNegativeButton("取消", null).show();
		} else {
			JToastKit.getInstance().showMessage("点选的是添加图片");
		}
		return true;
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		// 如果list元素数量没到上传最大值，则添加加号图片
		// 刷新adapter写与此主要防止用户直接按返回键，导致加号显示与否无法判断
		if (imageList.size() < MAX_IMAGECOUNT) {
			ImageModel model = new ImageModel();
			model.setSpareImage(R.drawable.addimage);
			imageList.add(model);
		}
		adapter.notifyDataSetChanged(); // 通知adapter刷新
	}
}
